import { useEffect, useState, useRef, useCallback } from "react";

const useScroll = (ref) => {

  const frame = useRef(20);
  const [state, setState] = useState({
    offset: 0,
    delta:  0,
  });

  const setRafState = useCallback((value) => {
    if (frame.current) {
      cancelAnimationFrame(frame.current);
    }

    frame.current = requestAnimationFrame(() => {
      setState(value);
    });
  }, []);


  const handler = useCallback(() => {
    if (ref.current) {
      const {scrollTop: curr} = ref.current;
      const {offset: prev} = state;
      setRafState({
        offset: curr,
        delta: prev,
      });
    }
  }, []);

  const enable = () => {

    if (ref.current) {
      ref.current.style.overflowY = 'scroll';
      ref.current.addEventListener('scroll', handler, {
        capture: false,
        passive: true,
      });
    }
  }

  const disable = () => {
    cancelAnimationFrame(frame.current);
    if (ref.current) {
      ref.current.style.overflowY = 'hidden';
      ref.current.removeEventListener('scroll', handler);
    }
  };

  const scrollTo = (scrollOffset) => {

    scrollOffset = Math.max(0, scrollOffset);
    setState({...state, offset: scrollOffset});
    
    ref.current.scrollTop = scrollOffset;
  }

  useEffect(() => {
    enable();
    return disable;
  }, [ref]);

  return {state, enableScroll: enable, disableScroll: disable, scrollTo};
};

export default useScroll;